<template>
  <pageTabelLayout>
    <template #pageHeader>
      <div class="search-form isheader" v-if="headerShow">
        <div>
          <a-form size="small" :model="pageData" layout="inline">
            <a-form-item label="流转卡号" :style="{ width: '345px' }" label-col-flex="100px">
              <a-input allow-clear class="bacClass" v-model="pageData.flowCardCode"/>
            </a-form-item>
            <a-form-item label="布号" :style="{ width: '345px' }" label-col-flex="100px">
              <a-input allow-clear class="bacClass" v-model="pageData.clothCode"/>
            </a-form-item>
            <a-form-item label="色称" :style="{ width: '345px' }" label-col-flex="100px">
              <a-input allow-clear class="bacClass" v-model="pageData.colorName"/>
            </a-form-item>
            <a-form-item label="色号" :style="{ width: '345px' }" label-col-flex="100px">
              <a-input allow-clear class="bacClass" v-model="pageData.colorCode"/>
            </a-form-item>
            <a-form-item label="染整单号" :style="{ width: '345px' }" label-col-flex="100px">
              <a-input allow-clear class="bacClass" v-model="pageData.orderCode"/>
            </a-form-item>
          </a-form>
        </div>

      </div>

      <div class="my-divisders">
        <a-divider orientation="center">
          <icon-double-up v-if="headerShow" @click="headerShow = false" :strokeWidth="2" :size="18"/>
          <icon-double-down v-else @click="headerShow = true" :strokeWidth="2" :size="18"/>
        </a-divider>
      </div>
      <div style="float: right;">
        <Toolbar :items="toolbarList" @select="selectHandler" @del="deleteHandler" @audit="audits"
                 @counter="audits1">
        </Toolbar>
      </div>
    </template>
    <template #pageTabel>
      <a-tabs   :lazy-load="true" :justify="true" :default-active-key="tabsKeys" @change="tabsChanges">
        <a-tab-pane title="未处理" :key="1">
          <AgGridVuesCopys :rowHeight="33" :headerHeight="33" :suppressCopyRowsToClipboard="true"
                           rowSelection="multiple" @grid-ready="gridReady" style="height:calc(100% - 45px)"
                           :defaultColDef="defaultColDef"
                           class='ag-theme-alpine' :rowData="tableDataList" :columnDefs="tc" :localeText="localeText1">
          </AgGridVuesCopys>
          <paginationCopys :page-size-options="pagingList1" :total="total" show-total show-jumper show-page-size
                           @change="PageSize" @page-size-change="change" style="justify-content: center"
                           :page-size="pagination.pageSize" :current="pagination.page"/>
        </a-tab-pane>
        <a-tab-pane title="已处理" :key="2">
          <AgGridVuesCopys :rowHeight="33" :headerHeight="33" :suppressCopyRowsToClipboard="true"
                           rowSelection="multiple" @grid-ready="gridReady2" style="height:calc(100% - 45px)"
                           :defaultColDef="defaultColDef2"
                           class='ag-theme-alpine' :rowData="tableDataList2" :columnDefs="tc2"
                           :localeText="localeText1">
          </AgGridVuesCopys>
          <paginationCopys :page-size-options="pagingList1" :total="total1" show-total show-jumper show-page-size
                           @change="PageSize" @page-size-change="change" style="justify-content: center"
                           :page-size="pagination.pageSize" :current="pagination.page"/>
        </a-tab-pane>
      </a-tabs>

    </template>
    <a-drawer :drawer-style="{ 'zIndex': 9999 }" :mask-closable="false" height="80%" :visible="pageData.showAdd8"
              unmountOnClose @ok="sideOk" @cancel="pageData.showAdd8 = false" cancel-text='关闭' ok-text='保存'
              placement="bottom">
      <template #title>
        刷坯
      </template>
      <div style="float: left;margin-top: 10px;width:100%">
        <table class="tableCla">
          <thead>
          <tr>
            <th colspan="7">分纱</th>
            <th colspan="8">库存</th>
          </tr>
          <tr>
            <th>缸数</th>
            <th>匹数</th>
            <th>重量</th>
            <!-- <th>设备</th> -->
            <th>织厂</th>
            <th>坯布编号</th>
            <th>纱批</th>
            <th>等级</th>
            <th>机台</th>
            <th>匹数</th>
            <th>退批备注</th>
            <th>来料单号</th>
            <th>库存匹数</th>
            <th>库存欠坯</th>
            <th>操作</th>
          </tr>
          </thead>
          <tbody>
          <tr v-for="(item, index) in pageData.cfList4" :key="index"
              :class="{ 'bacCla': item['retainingNum'] == '合计' }">
            <td :rowspan="item['rowLen']" v-if="item['colShow']">{{
                item['retainingNum'] == undefined ? "" : item['retainingNum']
              }}
            </td>
            <td :rowspan="item['rowLen']" v-if="item['colShow']">{{
                item['greyHouseNum'] == undefined ? "" : item['greyHouseNum']
              }}
            </td>
            <td :rowspan="item['rowLen']" v-if="item['colShow']">{{
                item['retainingWeight'] == undefined ? "" : item['retainingWeight']
              }}
            </td>
            <td :rowspan="item['rowLen']" v-if="item['colShow']">{{
                item['firm'] == undefined ? "" :
                    item['firm']
              }}
            </td>
            <td :rowspan="item['rowLen']" v-if="item['colShow']">{{
                item['greyCode'] == undefined ? "" : item['greyCode']
              }}
            </td>
            <td :rowspan="item['rowLen']" v-if="item['colShow']">{{
                item['yarnBatch'] == undefined ? "" : item['yarnBatch']
              }}
            </td>
            <td>
              <a-select popup-container="html" class="bacClass" :loading="loading" :allowClear="true"
                        :filter-option="false"
                        v-if="item['rankName'] != undefined" allow-search @focus="focusSelKW(item)"
                        style="width:100px" v-model="item.rankName" @change="changes(item)">
                <a-option v-for="item in pageData.nameListKW" :value="item['grade']">{{
                    item['grade']
                  }}
                </a-option>
              </a-select>
              <!-- <a-select popup-container="html"  class="bacClass" :loading="loading" v-model="item.rankName"
                  v-if="item['rankName'] != undefined" :filter-option="false" allow-search allow-clear
                  @focus="focusSel4_1(item)" @change="changeCf4_1(item)">
                  <a-option v-for="item in pageData.nameList4_1" :value="item['grade']">{{
                      item['grade']
                  }}</a-option>
              </a-select> -->
            </td>
            <td>{{ item['greyMachineCode'] == undefined ? "" : item['greyMachineCode'] }}</td>
            <td>
              <a-input-number v-model="item.retainingHouseNum" class="bacClass" @change="changes1(item)"
                              v-if="item['retainingHouseNum'] != undefined" :min="0"></a-input-number>
            </td>
            <td>{{ item['returnRemark'] == undefined ? "" : item['returnRemark'] }}</td>
            <td>{{ item['warrantCode'] == undefined ? "" : item['warrantCode'] }}</td>
            <td>{{ item['reyNum'] == undefined ? "" : item['reyNum'] }}</td>
            <td>{{ item['ownNum'] == undefined ? "" : item['ownNum'] }}</td>
            <td>
              <a-button type="primary" v-if="item['colShow'] && item['retainingNum'] != '合计'"
                        @click="addRow(item, index)">新增
              </a-button>
              <a-button type="primary" status="danger"
                        v-if="(!item['colShow']) && item['retainingNum'] != '合计'"
                        @click="delRow(item)">删除
              </a-button>
            </td>
          </tr>

          </tbody>
        </table>
      </div>

      <!-- <AgGridVuesCopys style="height:100%;width: 100%;float: left;" class="ag-theme-alpine" :columnDefs="tc3"
          :rowData="tableDataList3" :defaultColDef="defaultColDef3" :enableColResize="true" rowSelection="multiple"
          @grid-ready="gridReady3">
      </AgGridVuesCopys> -->
    </a-drawer>

  </pageTabelLayout>
</template>
<script setup lang="ts">
import {
  useTable,
  useRowKey,
  useTableColumn,
  usePagination,
  useRowSelection,
} from "@/hooks/table";
import {ref, reactive} from "vue"
import {post, get} from "@/api/http"
import {localeText} from '@/api/aggridZw'

import Toolbar from "@/components/Toolbar.vue"
import {Message, Modal} from "@arco-design/web-vue"
import CorporateSectorCascader from '@/components/corporateSectorCascader/inde.vue'
import {FormInstance} from "@arco-design/web-vue/es/form";
import {EXELTABLE} from '@/utils/exportEXCEL';
import {pagingList} from "@/api/paging";
import {baseURL} from '../../../api/axios.config'
import axios from "axios";

const toolbarList: any = ref(['查询', '删除', '审核'])
let isIDs: any = ref(1);


function PageSize(val: any) {
  if (isIDs.value == 1) {
    pagination.page = val
    doRefresh();
  } else if (isIDs.value == 2) {
    pagination2.page = val
    doRefresh1();
  }
}

function change(val: any) {
  if (isIDs.value == 1) {
    pagination.pageSize = val
    doRefresh();
  } else {
    pagination2.pageSize = val
    doRefresh1();
  }
}


const headerShow = ref(true)

const tableDataList = ref([])

const tableDataList2: any = ref([])
const tableDataList3: any = ref([])

const gridOption = ref()
const gridReady = (params: any) => {
  gridOption.value = params.api
}

const gridOption2 = ref()
const gridReady2 = (params: any) => {
  gridOption2.value = params.api
}

const gridOption3 = ref()
const gridReady3 = (params: any) => {
  gridOption3.value = params.api
}

const defaultColDef = {
  sortable: true,
  resizable: true,
  filter: true,
}

const defaultColDef2 = {
  sortable: true,
  resizable: true,
  filter: true,
}
const defaultColDef3 = {
  sortable: true,
  resizable: true,
  filter: true,
}

const localeText1: any = ref(localeText)

class ShowCellRenderer {
  init(params: any) {
    const cellBlank = !params.value;
    if (cellBlank) {
      return;
    }

    this.ui = document.createElement('div');
    this.ui.innerHTML =
        '<div class="show-name">' +
        params.value.name +
        '' +
        '</div>' +
        '<div class="show-presenter">' +
        params.value.presenter +
        '</div>';
  }

  getGui() {
    return this.ui;
  }

  refresh() {
    return false;
  }
}

const tc = [
  {
    showRowGroup: 'hide_def',
    "headerName": "",
    "checkboxSelection": true,
    "headerCheckboxSelection": true,
    "pinned": "left",
    "width": 50,
    resizable: false,
    filter: false,
    sortable: false,
    minWidth: 50,
    maxWidth: 50,
    lockPosition: "left",
  },
  // {
  //     headerName: '序号',
  //     field: 'recordCode',
  //     width: 150,
  //     filter: 'recordCode',
  // },
  {
    headerName: '流转卡号',
    field: 'flowCardCode',
    width: 150
  },
  {
    headerName: '染整单号',
    field: 'orderCode',
    width: 150
  },
  {
    headerName: '布号',
    field: 'clothCode',
    width: 150
  },
  {
    headerName: '色称',
    field: 'colorName',
    width: 150
  },
  {
    headerName: '色号',
    field: 'colorCode',
    width: 150
  },
  {
    headerName: '匹数',
    field: 'houseNum',
    width: 150
  },
  {
    headerName: '重量',
    field: 'flowCardWeight',
    width: 150
  },
  {
    headerName: '齐坯情况',
    field: 'fullState',
    width: 150,
    cellRenderer: {
      template: `
        <a-space>
          <el-tag v-if="fullState == 1" type="success" class="gesture">√</el-tag>
          <el-tag v-if="fullState == 0" type="success" class="gesture">欠坯</el-tag>
        </a-space>
      `,
      setup(props: any) {
        return {
          fullState: props.params.data.fullState
        }
      }
    }
  },

  {
    headerName: '状态',
    field: 'auditState',
    pinned: 'right',
    width: 110,
    cellRenderer: {
      template: `
        <a-space>
          <el-tag type="success" class="gesture">未审核</el-tag>
        </a-space>
      `,
      setup(props: any) {
        return {
          auditState: props.params.data.auditState,
          barcodeState: props.params.data.barcodeState
        }
      }
    }
  },
  // {
  //     headerName: '操作',
  //     field: 'id',
  //     pinned: 'right',
  //     width: 100,
  //     cellRenderer: {
  //         template: `
  //         <el-button style="color:#165dff;" @click="a" class="gesture" link>刷坯</el-button>
  //         `,
  //         setup(props: any) {
  //             const a = () => {
  //                 editHandler(props.params.data)
  //             }
  //             return {
  //                 a
  //             }
  //         }
  //     }
  // }
]

const tc2 = [
  {
    showRowGroup: 'hide_def',
    "headerName": "",
    "checkboxSelection": true,
    "headerCheckboxSelection": true,
    "pinned": "left",
    "width": 50,
    resizable: false,
    filter: false,
    sortable: false,
    minWidth: 50,
    maxWidth: 50,
    lockPosition: "left",
  },
  {
    headerName: '流转卡号',
    field: 'flowCardCode',
    width: 150
  },
  {
    headerName: '染整单号',
    field: 'orderCode',
    width: 150
  },
  {
    headerName: '布号',
    field: 'greyCode',
    width: 150
  },
  {
    headerName: '色称',
    field: 'colorName',
    width: 150
  },
  {
    headerName: '色号',
    field: 'colorCode',
    width: 150
  },
  {
    headerName: '匹数',
    field: 'houseNum',
    width: 150
  },
  {
    headerName: '重量',
    field: 'flowCardWeight',
    width: 150
  },
  {
    headerName: '齐坯情况',
    field: 'fullState',
    width: 150,
    cellRenderer: {
      template: `
        <a-space>
          <el-tag v-if="fullState == 1" type="success" class="gesture">√</el-tag>
          <el-tag v-if="fullState == 0" type="success" class="gesture">欠坯</el-tag>
        </a-space>
      `,
      setup(props: any) {
        return {
          fullState: props.params.data.fullState
        }
      }
    }
  },

  {
    headerName: '状态',
    field: 'auditState',
    pinned: 'right',
    width: 110,
    cellRenderer: {
      template: `
        <a-space>
          <el-tag type="success" class="gesture">已审核</el-tag>
        </a-space>
      `,
      setup(props: any) {
        return {
          auditState: props.params.data.auditState,
          barcodeState: props.params.data.barcodeState
        }
      }
    }
  },
]
const tc3: any = [
  {
    showRowGroup: 'hide_def',
    "headerName": "",
    "checkboxSelection": true,
    "headerCheckboxSelection": true,
    "pinned": "left",
    "width": 50,
    resizable: false,
    filter: false,
    sortable: false,
    minWidth: 50,
    maxWidth: 50,
    lockPosition: "left",
  },
  {
    headerName: '分纱',
    field: 'circulatCard',
    width: 1040,
    children: [
      {
        headerName: '缸数',
        field: 'retainingNum',
        width: 130,
        cellclassRules: {'show-cell': true},
        celIRenderer: ShowCellRenderer,
        // cellRendererParams: {
        //     mergeFunction: (params: any) => {
        //         const data = params.api.getRowNode(params.node.id).data;
        //         if (data.merge) {
        //             return null; // 返回 null 表示当前单元格不显示内容
        //         } else {
        //             return params.value;
        //         }
        //     }
        // },
        rowSpan:
            (param: any) => {
              if (param.data.show) {
                return rowSpan(param)
              }
              return 1
            },
      },
      {
        headerName: '匹数',
        field: 'greyHouseNum',
        width: 130,
        cellclassRules: {'show-cell': true},
        // celIRenderer: ShowCellRenderer,
        rowSpan: (param: any) => {
          if (param.data.show) {
            return rowSpan(param)
          }
          return 1
        },
      },
      {
        headerName: '重量',
        field: 'retainingWeight',
        width: 130,
        cellclassRules: {'show-cell': true},
        // celIRenderer: ShowCellRenderer,
        rowSpan: (param: any) => {
          if (param.data.show) {
            return rowSpan(param)
          }
          return 1
        },
      },
      {

        headerName: '织厂',
        field: 'firm',
        width: 130,
        cellclassRules: {'show-cell': true},
        // celIRenderer: ShowCellRenderer,
        rowSpan: (param: any) => {
          if (param.data.show) {
            return rowSpan(param)
          }
          return 1
        },
      },

      {
        headerName: '坯布编号',
        field: 'greyCode',
        width: 130,
        cellclassRules: {'show-cell': true},
        rowSpan: (param: any) => {
          if (param.data.show) {
            return rowSpan(param)
          }
          return 1
        },
      },
      {
        headerName: '纱批',
        field: 'yarnBatch',
        width: 130,
        cellclassRules: {'show-cell': true},
        rowSpan: (param: any) => {
          if (param.data.show) {
            return rowSpan(param)
          }
          return 1
        },
      },
    ]
  },
  {
    headerName: '库存',
    field: 'circulatCard',
    width: 1040,
    children: [
      {
        headerName: '等级',
        field: 'rankName',
        width: 130,
        cellRenderer: {
          template: `
            <a-select popup-container="html" class="bacClass" :loading="loading" :allowClear="true"
                      :filter-option="false" allow-search @focus="focusSelKW" v-model="mydata.rankName"
                      @change="changes(ress)">
              <a-option v-for="item in pageData.nameListKW" :value="item['grade']">{{
                  item['grade']
                }}
              </a-option>
            </a-select>`,
          setup(props: any) {
            const mydata = ref(props.params.data);
            const res = reactive<{
              storageId: any,
            }>({
              storageId: null,
            })

            return {
              changes,
              res,
              pageData,
              reactive,
              focusSelKW,
              mydata
            }
          }
        }
      },
      {
        headerName: '机台',
        field: 'greyMachineCode',
        width: 130
      },

      {
        headerName: '匹数',
        field: 'retainingHouseNum',
        width: 130,
        cellRenderer: {
          template: `
            <a-input-number v-model="mydata.retainingHouseNum" class="bacClass" @change="changes(ress)"
                            :min="0"></a-input-number>`,
          setup(props: any) {
            const mydata = ref(props.params.data);
            const res = reactive<{
              storageId: any,
            }>({
              storageId: null,
            })
            const pageData = reactive<{
              nameListKW: any[],
            }>({
              nameListKW: [],
            });

            return {
              changes,
              res,
              pageData,
              reactive,
              mydata
            }
          }
        }
      },
      {

        headerName: '退批备注',
        field: 'returnRemark',
        width: 130,
      },

      {
        headerName: '来料单号',
        field: 'warrantCode',
        width: 130,
      },
      {
        headerName: '库存匹数',
        field: 'reyNum',
        width: 130,
      },
      {
        headerName: '库存欠坯',
        field: 'ownNum',
        width: 130
      },
      {
        headerName: '操作',
        field: 'idd',
        // pinned: 'right',
        width: 100,
        cellRenderer: {
          template: `
            <el-button style="color:red;" @click="a" class="gesture" link>删除</el-button>`,
          setup(props: any) {
            const a = () => {
              tableDataList3.value.splice(props.params.rowIndex, 1);
              nextTick(() => {
                gridOption3.value.setRowData(tableDataList3.value)
              })

            }
            return {
              a
            }
          }
        }
      }
    ]
  }
]
const rowSpan = (param: any) => {
  const arr = ["retainingNum", "greyHouseNum", "retainingWeight", "firm", "greyCode", "yarnBatch"];
  if (arr.indexOf(param.column.colId) !== -1) {
    // 需要校验的字段
    const data = arr.slice(0, arr.indexOf(param.column.colId) + 1);
    // 每一条第一次出现时对应的索引
    const first = tableDataList3.value.findIndex((item: any) => {
      return data.every(v => item[v] === param.data[v]);
    });
    // console.log(data, '查验rowspan的问题', first);

    if (param.node.childIndex === first) {
      // 同一条出现的条数
      const rowspan = tableDataList3.value.filter((item: any) => {
        return data.every(v => item[v] === param.data[v]);
      }).length;
      console.log('这是合并方法', rowspan);
      return rowspan;
    } else {
      return 1;
    }
  }
  // let ob={}
  // ob[param.data.key]
  // if (param.data.show) {
  //     return 3;
  // } else {
  //     return 1;
  // }
  // console.log(rowspan,'这个合并的值到底是多少');
}

const objectOP = reactive<{}>
({});
const pageData = reactive<{
  dutymachineState: any,
  sideTitle: string,
  showAdd8: boolean,
  pageLoading: boolean,

  flowCardCode: any,
  clothCode: any,
  colorName: any,
  colorCode: any,
  orderCode: any,

  nameList: any[],
  nameList1: any[],
  nameList2: any[],
  nameListKW: any[],
  cfList4: any[],
}>({
  sideTitle: "新增收货单",
  dutymachineState: 0,
  showAdd8: false,
  pageLoading: false,

  flowCardCode: '',
  clothCode: '',
  colorName: '',
  colorCode: '',
  orderCode: '',

  nameList: [],
  nameList1: [],
  nameList2: [],
  nameListKW: [],
  cfList4: []
});

const editHandler = (record: any) => {
  console.log(record);
  post({
    url: "aps/matchBatchgrey/getList",
    data: {flowCardCode: record.flowCardCode}
  })
      .then(({data, code}: any) => {
        if (code === 200) {
          pageData.cfList4 = []
          let rowData = data
          let rowOb = {}
          // 分组 planOrderDetailOneId下是一个合计 {planOrderDetailOneId：[{}]}
          rowData.forEach(function (o: any, index: any) {
            if (rowOb[o['planOrderDetailId']] == undefined) {
              rowOb[o['planOrderDetailId']] = []
              rowOb[o['planOrderDetailId']].push(o)
            } else {
              rowOb[o['planOrderDetailId']].push(o)
            }
          })
          console.log(rowOb);
          //拆分分组 按顺序push  [{},{}]   rowLen 需要合计行数   colShow 是否需要显示列
          for (let key in rowOb) {
            let totalgreyHouseNum = 0
            let totalretainingWeight = 0
            rowOb[key].forEach(function (o: any, index: any) {
              o['rowLen'] = rowOb[key].length
              o['colShow'] = index == 0 ? true : false
              totalgreyHouseNum += parseFloat(o['greyHouseNum'])
              totalretainingWeight += parseFloat(o['retainingWeight'])
              pageData.cfList4.push(o)
            })
            let ob = {}
            ob['retainingNum'] = '合计'
            ob['greyHouseNum'] = totalgreyHouseNum
            ob['retainingWeight'] = totalretainingWeight
            ob['rowLen'] = 1
            ob['colShow'] = true
            pageData.cfList4.push(ob)

          }
          console.log(pageData.cfList4);

        }
      })
      .catch(console.log).finally(() => {
    pageData.pageLoading = false
  })
  pageData.showAdd8 = true;

}

const selectHandler = () => {
  if (tabsKeys.value == 1) {
    doRefresh()
  } else if (tabsKeys.value == 2) {
    doRefresh1()
  }
}

const tabsKeys = ref(1)

const tabsChanges = (e: any) => {
  tabsKeys.value = e
  if (e == 1) {
    toolbarList.value = ['查询', '删除', '审核']
  } else if (e == 2) {
    toolbarList.value = ['查询', '反审']
  }
}

// 新增事件
const formRef = ref<FormInstance>();
const sideOk = () => {
  // formRef.value?.validate().then((err) => {
  //     if (!err) {
  // if (pageData.sideTitle === "新增收货单") {
  pageData.cfList4.forEach((item: any) => {
    if (item.greyHouseNum == null) {
      item.greyHouseNum = 0
    }
    if ((item['id'] + "").indexOf('add') != -1) {
      item['id'] = null
    }

  })
  pageData.cfList4 = pageData.cfList4.filter(function (o: any) {
    return o['retainingNum'] != '合计'
  })
  post({
    url: "aps/circulatCard/updateFullState",
    data: pageData.cfList4
  }).then((res: any) => {
    if (res.code === 200) {
      formRef.value?.resetFields();
      pageData.showAdd8 = false;
      Message.success({
        content: "刷坯成功",
        duration: 5000,
      });
      doRefresh();
    } else {
      Message.error({
        content: res.message,
        duration: 5000,
      });
    }
  })
  // }
  //     }
  // })
}
// 收货来源下拉框下拉数据
const focusSel = () => {
  selCxAll({"codeType": ""});
}
const options = ref<any>(pageData.nameList);
const loading = ref(false);
const handleSearch = (value: any) => {
  if (value) {
    const ob = {codeType: value, deleteState: 0}
    loading.value = true;
    selCxAll(ob);
    options.value = pageData.nameList;
    loading.value = false;
  } else {
    options.value = []
  }
};

function selCxAll(val: any) {
  post({
    url: "/dict/dictTypeDetail/getList",
    data: {codeType: 30}
  }).then(({data, code}: any) => {
    if (code === 200) {
      pageData.nameList = data;
    } else {
      Message.error({
        content: "查询失败！",
        duration: 5000,
      });
    }
  });
}

// 未审核页面审核方法
const audits = () => {
  if (gridOption.value.getSelectedRows().length === 0) {
    Message.error('请先勾选')
    return;
  }
  Modal.confirm({
    title: '系统提示',
    content: '是否审核此订单',
    onOk() {
      post({
        url: "aps/circulatCard/audit",
        // data: auditStateId,
        data: gridOption.value.getSelectedRows().map((item: any) => {
          return {id: item.id, auditState: 1}
        })
      }).then((res: any) => {
        if (res.code === 200) {
          doRefresh();
          Message.success('审核通过')
          // selectedRowKeys.value = []
        } else {
          Message.error(res.message)
        }
      })
    }
  })
}
// 删除事件
const deleteHandler = () => {
  if (gridOption.value.getSelectedRows().length === 0) {
    Message.error('请先勾选')
    return;
  }
  Modal.confirm({
    title: "系统提示",
    content: "确认删除选中的数据?",
    onOk() {
      post({
        url: "aps/circulatCard/delete",
        data: gridOption.value.getSelectedRows().map((o: any) => {
          return o.id
        })
      }).then(({code, data, message}: any) => {
        if (code === 200) {
          Message.success({
            content: "删除成功",
            duration: 5000,
          });

          pagination.page = 1
          doRefresh();

        } else {
          Message.error({
            content: '删除失败',
            duration: 5000,
          });
        }

      });
    },
  });
};
// 查询事件
const total = ref(10);
const total1 = ref(10);
const pagingList1: any = ref(pagingList)
const page = ref(1);
const size = ref(10);

function doRefresh() {
  pageData.pageLoading = true
  post({
    url: "aps/circulatCard/getPage",
    data: {
      page: pagination.page,
      size: pagination.pageSize,
      flowCardCode: pageData.flowCardCode,
      clothCode: pageData.clothCode,
      colorName: pageData.colorName,
      colorCode: pageData.colorCode,
      orderCode: pageData.orderCode,
      cards: '',
      auditState: 0,
      deleteState: 0,
    },
  })
      .then(({data, code}: any) => {
        if (code === 200) {
          table.handleSuccess(data.list);
          gridOption.value.setRowData(data.list)
          total.value = data.total;
        }
      })
      .catch(console.log).finally(() => {
    pageData.pageLoading = false
  })
}

// 已审核查询
function doRefresh1() {
  pageData.pageLoading = true
  post({
    url: "aps/circulatCard/getPage",
    data: {
      page: pagination.page,
      size: pagination.pageSize,
      flowCardCode: pageData.flowCardCode,
      clothCode: pageData.clothCode,
      colorName: pageData.colorName,
      colorCode: pageData.colorCode,
      orderCode: pageData.orderCode,
      auditState: 1,
      deleteState: 0,
    },
  })
      .then(({data, code}: any) => {
        if (code === 200) {
          table.handleSuccess(data.list);
          gridOption2.value.setRowData(data.list)
          total1.value = data.total;
        }
      })
      .catch(console.log).finally(() => {
    pageData.pageLoading = false
  })
}

// 审核页面反审核方法
const audits1 = () => {
  if (gridOption.value.getSelectedRows().length === 0) {
    Message.error('请先勾选')
    return;
  }
  Modal.confirm({
    title: '系统提示',
    content: '是否审核此订单',
    onOk() {
      post({
        url: "aps/circulatCard/audit",
        // data: auditStateId,
        data: gridOption.value.getSelectedRows().map((item: any) => {
          return {id: item.id, auditState: 0}
        })
      }).then((res: any) => {
        if (res.code === 200) {
          doRefresh();
          Message.success('审核通过')
          // selectedRowKeys.value = []
        } else {
          Message.error(res.message)
        }
      })
    }
  })
}
const {selectedRowKeys, onSelectionChange} = useRowSelection();
const pagination = usePagination(doRefresh);
const pagination2 = usePagination(doRefresh1);
const table = useTable();
const rowKey = useRowKey("id");
const focusSelKW = (item: any) => {
  post({
    url: "wms/BlankStock/getGradeList",
    data: {
      customOrderCode: gridOption.value.getSelectedRows()[0].customOrderCode,
      // colorCode: gridOption.value.getSelectedRows()[0].colorCode,
      greyCode: item.greyCode
    }
  }).then(({data, code, message}: any) => {
    if (code === 200) {
      pageData.nameListKW = data;
    } else {
      Message.error({
        content: message,
        duration: 5000,
      });
    }
  });
}

const changes = (item: any) => {
  // if(tableCon.tableConter3[0].rankName != ''){}
  post({
    url: "aps/planOrder/getStockByGrade",
    data: {
      greyCode: item.greyCode,
      grade: item.rankName,
      houseNum: item.houseNum,
      customOrderCode: gridOption.value.getSelectedRows()[0].customOrderCode,
      // colorCode: gridOption.value.getSelectedRows()[0].colorCode,
      clothCode: gridOption.value.getSelectedRows()[0].clothCode,
      orderCode: gridOption.value.getSelectedRows()[0].orderCode
    }
  }).then(({data, code}: any) => {
    if (code === 200) {
      item.greyMachineCode = data.greyMachineCode
      item.greyHouseNum = data.greyHouseNum
      item.returnRemark = data.returnRemark
      item.warrantCode = data.warrantCode
      item.reyNum = data.reyNum
    } else {
      Message.error({
        content: "查询失败！",
        duration: 5000,
      });
    }

  });

}
const changes1 = (item: any) => {
  if (item.reyNum - item.retainingHouseNum > 0) {
    item.ownNum = 0
  } else {
    item.ownNum = item.reyNum - item.retainingHouseNum
  }
}

function delRow(item: any) {
  pageData.cfList4 = pageData.cfList4.filter(function (o: any) {
    return o['id'] != item['id']
  })
  pageData.cfList4.forEach(function (o: any) {
    if (o['planOrderDetailOneId'] == item['planOrderDetailOneId']) {
      o['rowLen']--
    }
  })

}

let idAdd = 0

function addRow(item: any, index: any) {
  idAdd++
  let ob = {
    "retainingNum": item['retainingNum'],
    "greyHouseNum": item['greyHouseNum'],
    "retainingWeight": item['retainingWeight'],
    "firm": item['firm'],
    "greyCode": item['greyCode'],
    "yarnBatch": item['yarnBatch'],
    "planOrderDetailOneId": item['planOrderDetailOneId'],
    "rankName": "",
    "greyMachineCode": "",
    "retainingHouseNum": 0,
    "returnRemark": "",
    "warrantCode": "",
    "reyNum": 0,
    "oweNum": 0,
    'rowLen': item['rowLen'] + 1,
    'colShow': false,
    "id": 'add' + idAdd
  }
  pageData.cfList4.forEach(function (o: any) {
    if (o['planOrderDetailOneId'] == item['planOrderDetailOneId']) {
      o['rowLen'] = o['rowLen'] + 1
    }
  })
  pageData.cfList4.splice(index + item['rowLen'] - 1, 0, ob);
  console.log(pageData.cfList4);

}


</script>
<script lang="ts">
export default {
  name: "ReceiptList0",
}
</script>
<style scoped lang="less">
:deep(.ag-cell) {
  border-right: 1px solid #dde2eb;
}

:deep(.ag-header-cell) {
  border-right: 1px solid #dde2eb;
}

:deep(.ag-cell-value) {
  user-select: initial;
  -moz-user-select: text;
  -ms-user-select: text;
  -webkit-user-select: text;
}

// :deep (col-id='retainingNum'),
// v-deep [col-id='greyHouseNum'],
// v-deep [col-id='retainingWeight'],
// v-deep [col-id='firm'],
// v-deep [col-id='greyCode'],
// v-deep [col-id='yarnBatch'] {
//     background: #fff;

//     // border-left: 1px solid lightgrey !important;
//     // border-right: 1px solid lightgrey !important;
//     // border-bottom: 1px solid lightgrey !important;
//     display: flex;
//     align-items: center;
//     justify-content: center;
//     height: 100%;
// }

.tableCla {
  display: block;
  border-collapse: collapse;
  width: 100%;
}

.tableCla th,
.tableCla td {
  border: 1px solid #cccccc;
  padding: 5px 10px;
}

.bacCla {
  background-color: #e5f1ff;
}
</style>
